package com.sys.ai.service.impl;

import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sys.ai.domain.AiSendHistory;
import com.sys.ai.fo.UpdateGroupNameByCodeFO;
import com.sys.ai.mapper.AiSendHistoryMapper;
import com.sys.ai.service.IAiSendHistoryService;
import com.sys.ai.vo.MessageHistoryVO;
import com.sys.common.annotation.DataScope;
import com.sys.common.core.domain.model.LoginUser;
import com.sys.common.utils.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.LocalDate;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;

/**
 * 发送记录Service业务层处理
 *
 * @author LGY
 * @date 2025-05-09
 */
@Slf4j
@Service
public class AiSendHistoryServiceImpl extends ServiceImpl<AiSendHistoryMapper, AiSendHistory> implements IAiSendHistoryService {
    @Autowired
    private AiSendHistoryMapper aiSendHistoryMapper;

    /**
     * 查询发送记录
     *
     * @param id 发送记录主键
     * @return 发送记录
     */
    @Override
    public AiSendHistory selectAiSendHistoryById(String id) {
        return this.getById(id);
    }

    /**
     * 查询发送记录列表
     *
     * @param aiSendHistory 发送记录
     * @return 发送记录
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<AiSendHistory> selectAiSendHistoryList(AiSendHistory aiSendHistory) {
        return aiSendHistoryMapper.selectAiSendHistoryList(aiSendHistory);
    }

    /**
     * 新增发送记录
     *
     * @param aiSendHistory 发送记录
     * @return 结果
     */

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void insertAiSendHistory(AiSendHistory aiSendHistory) {
        this.save(aiSendHistory);
    }

    /**
     * 修改发送记录
     *
     * @param aiSendHistory 发送记录
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void updateAiSendHistory(AiSendHistory aiSendHistory) {
        this.updateById(aiSendHistory);
    }

    /**
     * 批量删除发送记录
     *
     * @param ids 需要删除的发送记录主键
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void deleteAiSendHistoryByIds(String[] ids) {
        this.removeBatchByIds(Arrays.asList(ids));
    }

    @Override
    public List<AiSendHistory> findLatestFiveByGroupCode(String requestAnswerGroupCode, LoginUser currentUser) {
        List<AiSendHistory> aiSendHistoryList = new LambdaQueryChainWrapper<>(baseMapper)
                .eq(AiSendHistory::getGroupCode, requestAnswerGroupCode)
                .eq(AiSendHistory::getCreateBy, currentUser.getId())
                .orderByDesc(AiSendHistory::getCreateTime)
                .list();
        if (!CollectionUtils.isEmpty(aiSendHistoryList) && aiSendHistoryList.size() >= 5) {
            aiSendHistoryList = aiSendHistoryList.subList(0, 5);
        }
        if (!CollectionUtils.isEmpty(aiSendHistoryList)) {
            aiSendHistoryList.sort(Comparator.comparing(AiSendHistory::getCreateTime));
        }
        return aiSendHistoryList;
    }

    @Override
    public List<AiSendHistory> findAllByGroupCode(String requestAnswerGroupCode) {
        return new LambdaQueryChainWrapper<>(baseMapper)
                .eq(AiSendHistory::getGroupCode, requestAnswerGroupCode)
                .eq(AiSendHistory::getCreateBy, SecurityUtils.getUserId())
                .orderByAsc(AiSendHistory::getCreateTime)
                .list();
    }

    @Override
    public List<MessageHistoryVO> listAllMySelf(String appId) {
        String userId = SecurityUtils.getUserId();
        List<MessageHistoryVO> messageHistoryVOList = baseMapper.listAllMySelf(userId, appId);
        if (CollectionUtils.isEmpty(messageHistoryVOList)) {
            return messageHistoryVOList;
        }
        messageHistoryVOList.forEach(messageHistoryVO -> {
            // sendTime 是今天的
            // sendTime 是本月的
            if (Objects.equals(LocalDate.now(), messageHistoryVO.getSendTime().toLocalDate())) {
                messageHistoryVO.setType(0);
            } else if (Objects.equals(LocalDate.now().getMonth(), messageHistoryVO.getSendTime().toLocalDate().getMonth())) {
                messageHistoryVO.setType(1);
            } else {
                messageHistoryVO.setType(2);
            }
        });
        return messageHistoryVOList;
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void deleteByCode(String groupCode) {
        new LambdaUpdateChainWrapper<>(baseMapper)
                .eq(AiSendHistory::getGroupCode, groupCode)
                .remove();
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void updateGroupNameByCode(UpdateGroupNameByCodeFO updateGroupNameByCodeFO) {
        new LambdaUpdateChainWrapper<>(baseMapper)
                .eq(AiSendHistory::getGroupCode, updateGroupNameByCodeFO.getGroupCode())
                .set(AiSendHistory::getGroupName, updateGroupNameByCodeFO.getNewGroupName())
                .update();
    }
}